package core

import (
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
	"log"
	"os"
	"path/filepath"
	"strings"
)

func InitFramework(registerRouter func(r *gin.Engine)) {
	err, cfg := initConfiguration("./application.properties")
	if err != nil {
		log.Fatal(err)
	}
	router := initRouter(cfg, registerRouter)
	router.SetFuncMap(GetFuncMap())
	router.Run(cfg.App.ServerPort)
}

func initRouter(cfg *Configuration, registerRouter func(r *gin.Engine)) *gin.Engine {
	router := gin.Default()
	router.Static(cfg.App.StaticPrefix, cfg.App.StaticRoot)
	router.SetFuncMap(GetFuncMap())
	if cfg.App.TemplateDir != "" {
		templateFiles := loadAllTemplates(cfg.App.TemplateDir)
		if len(templateFiles) > 0 {
			router.LoadHTMLFiles(templateFiles...)
		}
		router.Delims("{{", "}}")
	}
	store := cookie.NewStore([]byte("secret"))
	router.Use(sessions.Sessions("mySession", store))
	registerRouter(router)

	return router
}

func loadAllTemplates(dir string) []string {
	templateFiles := make([]string, 0)
	filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
		if strings.HasSuffix(info.Name(), ".html") {
			log.Println("加载模板文件", path)
			if _, err := os.Stat(path); err != nil {
				log.Println(path, err.Error())
			}
			templateFiles = append(templateFiles, path)
		}
		return nil
	})
	return templateFiles
}
